package org.yelongframework.qrcode.impl.zxing;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码工具类
 * 
 * @since 1.0.0
 */
public final class ZxingQRCodeUtils {

	private static final Writer writer = new MultiFormatWriter();

	private ZxingQRCodeUtils() {
	}

	/**
	 * 生成二维码
	 * 
	 * @param content            内容
	 * @param width              宽度
	 * @param height             高度
	 * @param encodeQRCodeConfig 配置
	 * @return 二维码的图片流
	 * @see ImageIO#write(java.awt.image.RenderedImage, String, java.io.File)
	 *      第二个参数为文件的格式，如 jpg,png 等
	 */
	public static BufferedImage encodeReturnBufferedImage(String content, int width, int height,
			ZxingEncodeQRCodeConfig encodeQRCodeConfig) throws WriterException {
		if (null == encodeQRCodeConfig) {
			encodeQRCodeConfig = new ZxingEncodeQRCodeConfig();
		}
		BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, encodeQRCodeConfig.getHints());
		if (encodeQRCodeConfig.getMargin() > 0) {
			return MatrixToImageUtils.toBufferedImageRemoveWhiteBorderSetMargin(matrix, encodeQRCodeConfig.getMargin());
		} else if (encodeQRCodeConfig.isRemoveWhiteBorder()) {
			return MatrixToImageUtils.toBufferedImageRemoveWhiteBorder(matrix);
		}
		return MatrixToImageWriter.toBufferedImage(matrix);
	}

}
